#!/bin/bash

# 检查是否以 root 用户运行
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用 root 用户运行此脚本！"
    echo "尝试使用: sudo ./setup_openomics_service.sh"
    exit 1
fi

# 定义变量
SERVICE_NAME="openomics"
PYTHON_PATH=$(which python3)
APP_PATH="/home/kzlab/P_OpenOmics_V4.0/src/app.py"
WORKING_DIR="/home/kzlab/P_OpenOmics_V4.0/src"
USER_NAME="kzlab"

# 检查 Python 是否存在
if [ -z "$PYTHON_PATH" ]; then
    echo "错误：未找到 python3，请先安装 Python3！"
    exit 1
fi

# 检查 app.py 是否存在
if [ ! -f "$APP_PATH" ]; then
    echo "错误：未找到 $APP_PATH，请检查路径！"
    exit 1
fi

# 创建 systemd 服务文件
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=P_OpenOmics_V4.0 Application
After=network.target

[Service]
ExecStart=$PYTHON_PATH $APP_PATH
WorkingDirectory=$WORKING_DIR
User=$USER_NAME
Group=$USER_NAME
Restart=always
RestartSec=10
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
EOF

# 设置权限
chmod 644 "$SERVICE_FILE"

# 重新加载 systemd
systemctl daemon-reload

# 启用并启动服务
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

# 检查状态
echo "服务状态："
systemctl status "$SERVICE_NAME" --no-pager

echo ""
echo "✅ 配置完成！$SERVICE_NAME 已设置为开机自启动。"
echo "📜 查看日志：journalctl -u $SERVICE_NAME -b -f"